package com.rtmart.pdaservice;

import java.util.List;

import android.annotation.SuppressLint;
import android.net.wifi.*;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class WifiConnector {

    Handler mHandler;
    WifiManager wifiManager;

    /**
     * 向UI发送消息
     * @param info 消息
     */
    public void sendMsg(String info) {
        if (mHandler != null) {
            Message msg = new Message();
            msg.obj = info;
            mHandler.sendMessage(msg);// 向Handler发送消息
        } else {
            Log.e("wifi", info);
        }
    }

    // 构造函数
    public WifiConnector(WifiManager wifiManager) {
        this.wifiManager = wifiManager;
    }

    // 提供一个外部接口，传入要连接的无线网
    public void connect(String ssid, String password) {
        Thread thread = new Thread(new ConnectRunnable(ssid, password));
        thread.start();
    }

    // 查看以前是否也配置过这个网络
    private WifiConfiguration isExists(String SSID) {
        @SuppressLint("MissingPermission") List<WifiConfiguration> existingConfigs = wifiManager
                .getConfiguredNetworks();
        for (WifiConfiguration existingConfig : existingConfigs) {
            if (existingConfig.SSID.equals("\"" + SSID + "\"")) {
                return existingConfig;
            }
        }
        return null;
    }

    class ConnectRunnable implements Runnable {
        private String ssid;
        private String password;

        public ConnectRunnable(String ssid, String password) {
            this.ssid = ssid;
            this.password = password;
        }

        @Override
        public void run() {
            try {
                WifiConfiguration wifiConfiguration = isExists(ssid);
                if (wifiConfiguration != null) {
                    wifiManager.removeNetwork(wifiConfiguration.networkId);

                    wifiConfiguration.preSharedKey = "\"" + password + "\"";

                    int netID = wifiManager.addNetwork(wifiConfiguration);
                    boolean enabled = wifiManager.enableNetwork(netID, true);
                    sendMsg("enableNetwork status enable=" + enabled);
                    boolean connected = wifiManager.reconnect();
                    sendMsg("enableNetwork connected=" + connected);
                    sendMsg("连接成功!");
                    Log.d("WifiConnector", "success");
                }
            } catch (Exception e) {
                // TODO: handle exception
                sendMsg(e.getMessage());
                e.printStackTrace();
            }
        }
    }
}
